package com.herohead.backup;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

import com.herohead.json.JsonEmail;
import com.herohead.redis.GetRedisServer;
import com.herohead.redis.RedisKeys;
import com.herohead.redis.RedisVars;

public class SsidNotCloned {

	static List<String> noGroups = new ArrayList<String>();


	public static void main(String[] args) {
		// TODO Auto-generated method stub

		GetRedisServer grs = new GetRedisServer();
		//RedisVars.redisHost = grs.getRedisHost();
		RedisVars.redisHost = "localhost";
		Jedis jd = new Jedis(RedisVars.redisHost);
		try {
			grs.checkForRedis(jd);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.exit(1);
		}


		Jedis jdpl = new Jedis(RedisVars.redisHost);
		Transaction tx = jdpl.multi();

		//tx.sadd("s_prod:ssid:not:cloned", members);

		String fileInput = args[0];

		//String fileInput = "src/not_replicated.txt";
		File file = new File(fileInput);

		String fileTxt = null;
		try {
			fileTxt = FileUtils.readFileToString(file, "UTF-8");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		jd.del(RedisKeys.setProdSSIDNotCloned);
		jd.del(RedisKeys.setProdGroupNotCloned);
		jd.del(RedisKeys.hashProdSSIDNotCloned);
		String[] lines = fileTxt.split("\n");
		long totalSizeAmt = 0;
		String ssid;
		for (String line :lines) {
			if (line.contains("ssid")) {continue;}
			line = line.trim();
			line = line.replaceAll("\\s+", " ");
			ssid = line.split(" ")[0];
			String group = null;
			String totalSize = null;
			try {
				group = line.split(" ")[4];
				totalSize = line.split(" ")[5];
				System.out.println(ssid + " " + group);
				tx.sadd(RedisKeys.setProdSSIDNotCloned, ssid);
				tx.hset(RedisKeys.hashProdSSIDNotCloned,ssid,totalSize);
				tx.sadd(RedisKeys.setProdGroupNotCloned, group);
				totalSizeAmt = totalSizeAmt + Long.parseLong(totalSize);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				noGroups.add(ssid);
				System.out.println("Found no group");
			}

		}

		tx.set(RedisKeys.strProdSizeNotCloned, String.valueOf(totalSizeAmt));


		if (!noGroups.isEmpty()) {
			String body = "Here is the list of SSID with no Groups<br><br>";
			for (String b : noGroups) {
				body = body + b + "<br>";
			}
			JsonEmail jem = new JsonEmail("craig.david@mt.com","craig.david@mt.com","SSID Not CLoned - Error","smtp.mt.com",body,"1");
			jd.rpush(RedisKeys.lProdEmailQueue, jem.getJsonString());
		} else {
			System.out.println("No problems found");
		}

		tx.exec();
		jd.close();
		jdpl.close();


	}

}
